var racecar;
var keys;
var boost;

function start() {

  // Latitude/Longitude of race checkpoints, in the order the car
  // should drive by them.
  var startLat = 36.060, startLon = -112.112;
  var boostLat = 36.062, boostLon = -112.112;
  var edgeLat = 36.064, edgeLon = -112.112;
  var finishLat = 36.210, finishLon = -112.112;

  racecar = new Car;
  racecar.moveToPos(startLat, startLon);

  keys = new Keys;

  var course = new Course;
  course.setStartPos(startLat, startLon);
  course.addCheckPointPos(boostLat, boostLon);
  course.addCheckPointPos(edgeLat, edgeLon);
  course.setFinishPos(finishLat, finishLon);

  boost = new Flag("BOOST!", boostLat, boostLon);
}

function everyFrame() {
  handleKeys();
  detectCollisions();
}

function handleKeys() {
  if (keys.upIsPressed()) {
    racecar.accelerate();
  } else if (keys.downIsPressed()) {
    racecar.decelerate();
  }
  if (keys.leftIsPressed()) {
    racecar.turnLeft();
  } else if (keys.rightIsPressed()) {
    racecar.turnRight();
  }
}

function detectCollisions() {
  if (AlmostEquals(racecar.getLatitude(),
                   boost.getLatitude()) &&
      AlmostEquals(racecar.getLongitude(),
                   boost.getLongitude())) {
    racecar.setBoost(1000);
  }
}

function AlmostEquals(a, b) {
  if (Math.abs(a - b) < 0.0001) {
    return true;
  }
  return false;
}
